package com.wulian.user.controller;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wulian.common.controller.BaseController;
import com.wulian.common.dto.UserInfo;
import com.wulian.common.entity.SysUser;
import com.wulian.common.exception.BusinessException;
import com.wulian.common.util.JSONUtil;
import com.wulian.common.vo.ResultMoudel;
import com.wulian.user.dto.CompanyManagerResultDto;
import com.wulian.user.entity.CompanyManager;
import com.wulian.user.mapper.CompanyManagerMapper;
import com.wulian.user.service.CompanyManagerService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

/**
 * @author caifulin
 * @version 1.0
 * @Description:()
 * @date 2020/7/23 18:11
 */
@RestController
@RequestMapping("/company")
@Slf4j
@Api(value = "企业管理controller", tags = {"企业管理接口"})
public class CompanyManagerController extends BaseController<CompanyManager> {


    @Autowired
    private CompanyManagerMapper companyManagerMapper;

    @Autowired
    private CompanyManagerService companyManagerService;

    /**
     * 功能描述: <br>
     * 〈新增或修改
     * 新增企业时会创建对应的组织机构和用户权限
     * 修改时不能操作企业用户〉
     *
     * @Param:
     * @Return:
     * @Author: caifulin
     * @Date: 2020/10/26
     */
    @PostMapping("/save")
    public ResultMoudel save(@RequestBody CompanyManagerResultDto companyManager) {
        Integer userId = getCurrentUser().getSysUser().getUserId();
        ResultMoudel resultMoudel = new ResultMoudel();
        if (null == companyManager) {
            return resultMoudel.error("参数异常");
        }

        Date date = new Date();
        companyManager.setUpdateTime(date);
        companyManager.setDelFlag(0);
        companyManager.setManagerUserId(userId);
        Integer flag = 0;
        try {
            //操作前查询企业标记是否重复
            CompanyManager where = new CompanyManager();
            where.setCompanyLogo(companyManager.getCompanyLogo());
            where.setDelFlag(0);
            EntityWrapper<CompanyManager> companyManagerEntityWrapper = new EntityWrapper(where);
            List<CompanyManager> companyManagers = companyManagerService.selectList(companyManagerEntityWrapper);
            if (null != companyManagers && companyManagers.size() > 0) {
                if (companyManager.getCompanyId() == null) {//添加时企业标记已存在
                    log.info("添加时企业标记已存在" + JSONUtil.toJSON(companyManager));
                    return resultMoudel.error("企业标记已存在");
                }
                if (companyManagers.get(0).getCompanyId() != companyManager.getCompanyId()) {
                    log.info("修改时企业标记已存在" + JSONUtil.toJSON(companyManager));
                    return resultMoudel.error("企业标记已存在");
                }
            }
            flag = companyManagerService.save(companyManager);
        } catch (BusinessException b) {
            String message = b.getMessage();
            return resultMoudel.error(message);
        }

        if (flag == 0) {
            return resultMoudel.error("操作失败");
        }
        return resultMoudel.success("操作成功");
    }

    /**
     * 删除
     */
    @PostMapping("/delete")
    @ApiOperation(value = "删除企业", notes = "物理删除", httpMethod = "POST")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "int")
    )
    public ResultMoudel delete(@RequestBody CompanyManager companyManager) {
        ResultMoudel resultMoudel = new ResultMoudel();
        if (null == companyManager || null == companyManager.getCompanyId()) {
            return resultMoudel.error("参数异常");
        }
        Date nowDate = new Date();
        Integer userId = getCurrentUser().getSysUser().getUserId();

        companyManager.setDelFlag(1);
        companyManager.setUpdateTime(nowDate);
        companyManager.setManagerUserId(userId);

        Integer integer = companyManagerMapper.updateById(companyManager);
        if (integer == null) {
            return resultMoudel.error("操作失败");
        } else {
            return resultMoudel.success("操作成功");

        }
    }

    /**
     * 封存
     */
    @PostMapping("/fengcun")
    @ApiOperation(value = "封存企业", notes = "封存", httpMethod = "POST")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "int")
    )
    public ResultMoudel fengcun(@RequestBody CompanyManager companyManager) {
        UserInfo currentUser = getCurrentUser();
        companyManager.setStatus(1);
        ResultMoudel fencun = companyManagerService.fencun(companyManager, currentUser);
        return fencun;
    }
    /**
     * 解封
     */
    @PostMapping("/open")
    @ApiOperation(value = "解封企业", notes = "解封", httpMethod = "POST")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "int")
    )
    public ResultMoudel open(@RequestBody CompanyManager companyManager) {
        UserInfo currentUser = getCurrentUser();
        companyManager.setStatus(0);
        ResultMoudel fencun = companyManagerService.fencun(companyManager, currentUser);
        return fencun;
    }

    /**
     * 封存
     */
    @PostMapping("/openCompany")
    @ApiOperation(value = "启用企业", notes = "启用", httpMethod = "POST")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "id", value = "主键id", required = true, dataType = "int")
    )
    public ResultMoudel openCompany(@RequestBody CompanyManager companyManager) {
        ResultMoudel resultMoudel = new ResultMoudel();
        String[] roles = getCurrentUser().getRoles();
        if(roles == null){
            return resultMoudel.error("用户信息异常");
        }
        boolean falsg = false;
        for(String role: roles){
            if(role.equals("admin")){
                falsg = true;
                break ;
            }
        }
        if(! falsg){
            return resultMoudel.error("用户信息异常");
        }

        if (null == companyManager || null == companyManager.getCompanyId()) {
            return resultMoudel.error("参数异常");
        }
        Date nowDate = new Date();
        Integer userId = getCurrentUser().getSysUser().getUserId();

        companyManager.setStatus(0);
        companyManager.setUpdateTime(nowDate);
        companyManager.setManagerUserId(userId);

        Integer integer = companyManagerMapper.updateById(companyManager);
        if (integer == null) {
            return resultMoudel.error("操作失败");
        } else {
            return resultMoudel.success("操作成功");

        }
    }

    /**
     * 查询
     */
    @PostMapping("/find")
    public ResultMoudel find(@RequestBody CompanyManager companyManager) {
        ResultMoudel resultMoudel = new ResultMoudel();
        if (null == companyManager || null == companyManager.getCompanyId()) {
            return resultMoudel.error("参数异常");
        }
        CompanyManagerResultDto companyManagerResultDto = companyManagerMapper.selectByCompanyId(companyManager);
        if (null == companyManagerResultDto) {
            resultMoudel.error("查询信息不存在");
        }
        return resultMoudel.success(companyManagerResultDto);
    }

    /**
     * 分页查询
     */
    @PostMapping("/pageList")
    @ApiOperation(value = "企业管理分页查询", httpMethod = "POST", notes = "企业管理分页查询")
    @ApiImplicitParams(
            @ApiImplicitParam(name = "companyName", value = "企业名称", dataType = "string", required = false)
    )
    public ResultMoudel list(@RequestBody CompanyManager companyManager,
                             @RequestParam(required = false, defaultValue = "0") int num,
                             @RequestParam(required = false, defaultValue = "10") int pageSize) {
        ResultMoudel resultMoudel = new ResultMoudel();
        //分页构造器
        Page<CompanyManagerResultDto> page = new Page<CompanyManagerResultDto>(num, pageSize);
        List<CompanyManagerResultDto> companyManagerResultDtos = companyManagerMapper.pageList(companyManager, page);
        page.setRecords(companyManagerResultDtos);
        return new ResultMoudel().success(page);
    }

    /**
     * 功能描述: <br>
     * 〈验证企业标记是否存在〉
     *
     * @Param:
     * @Return:
     * @Author: caifulin
     * @Date: 2020/11/2
     */
    @PostMapping("/checkCompanyLogoExist")
    @ApiOperation(value = "验证企业标记是否存在", httpMethod = "POST")
    public ResultMoudel checkCompanyLogoExist(@RequestBody CompanyManagerResultDto companyManager) {
        ResultMoudel resultMoudel = new ResultMoudel();
        if (null == companyManager || null == companyManager.getCompanyLogo()) {
            return resultMoudel.error("参数异常");
        }
        //操作前查询企业标记是否重复
        CompanyManager where = new CompanyManager();
        where.setCompanyLogo(companyManager.getCompanyLogo());
        where.setDelFlag(0);
        EntityWrapper<CompanyManager> companyManagerEntityWrapper = new EntityWrapper(where);
        List<CompanyManager> companyManagers = companyManagerService.selectList(companyManagerEntityWrapper);
        if (null != companyManagers && companyManagers.size() > 0) {
            if (null == companyManager.getCompanyId()) {//添加时企业标记已存在
                log.info("添加时企业标记已存在" + JSONUtil.toJSON(companyManager));
                return resultMoudel.error("企业标记已存在");
            }
            if (companyManagers.get(0).getCompanyId() != companyManager.getCompanyId()) {
                log.info("修改时企业标记已存在" + JSONUtil.toJSON(companyManager));
                return resultMoudel.error("企业标记已存在");
            }
        }
        return resultMoudel.success("企业标记不存在");
    }
    
    
    /**
     * 查询
     */
    @PostMapping("/findCompany")
    public ResultMoudel findCompany() {
        ResultMoudel resultMoudel = new ResultMoudel();
        UserInfo currentUser = getCurrentUser();
        SysUser sysUser = currentUser.getSysUser();
        
        if(null == sysUser.getCompanyId()){
        	return resultMoudel.success(null);
        }
        
        //公司信息
        CompanyManager companyManager = companyManagerMapper.selectById(sysUser.getCompanyId());
        
        if(null != companyManager){
        	return resultMoudel.success(companyManager.getLogoUrl());
        }else{
        	return resultMoudel.success(null);
        }
        
    }
    
}